package heima.lm.oschina.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.text.TextUtils;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;

import heima.lm.oschina.BaseApplication;
import heima.lm.oschina.bean.Blog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

import static android.R.attr.entries;
import static android.R.attr.key;

/**
 * Created by Administrator on 2017/4/1.
 */

public class HttpUtils<T> {
    private Class<T> mClss;
    private CacheUtils mCacheUtils;

    public void getData(String url, Map<String, String> params, Class<T> clazz, OnHttpResponseListener<T> onHttpResponseListener) {
        //从缓存中获取
        this.mClss = clazz;
        url = getUrlFromMapParams(url, params);
        mCacheUtils = CacheUtils.getDefaultClient();
        String cache = mCacheUtils.getCache(Md5Utils.md5(url));
        if (!TextUtils.isEmpty(cache)) {
            Log.d("lm", "从存缓存中获取");
            T bean = XmlUtils.toBean(mClss, cache.getBytes());
            if (onHttpResponseListener != null)
                onHttpResponseListener.onSuccess(bean);
        } else {
            Log.d("lm", "从网络中获取");
            okHttpRequest(url, onHttpResponseListener);
        }
    }

    private void okHttpRequest(final String url, final OnHttpResponseListener<T> onHttpResponseListener) {
        Call call = getCall(url);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (onHttpResponseListener != null)
                    onHttpResponseListener.onFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                T bean = XmlUtils.toBean(mClss, result.getBytes());
                mCacheUtils.cache(Md5Utils.md5(url), result);
                if (onHttpResponseListener != null)
                    onHttpResponseListener.onSuccess(bean);
            }
        });
    }

    //从网络中获取call
    private Call getCall(String url) {
        // 2 构建Request
        Request.Builder builder = new Request.Builder().url(url);
        Request request = builder.build();
        // 3 通过Request构建Call
        return BaseApplication.mClient.newCall(request);
    }

    //获取新的url
    public static String getUrlFromMapParams(String url, Map<String, String> params) {
        // 做一些校验
        if (TextUtils.isEmpty(url) || params == null) {
            throw new IllegalArgumentException("url illegal or params is empty!");
        }
        if (params.size() == 0) {
            return url;
        }
        //http://192.168.1.100:8080/oschina/list/news/page0.xml
        StringBuilder sb = new StringBuilder();
        sb.append(url);
        // 取出参数拼接
        Set<Map.Entry<String, String>> entries = params.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            sb.append(entry.getKey()).append(entry.getValue()).append(".xml");
        }
        return sb.toString();
    }

    public static interface OnHttpResponseListener<T> {
        void onSuccess(T bean);

        void onFailure(Exception e);
    }

    public static boolean checkNet() {
        ConnectivityManager cm = (ConnectivityManager) BaseApplication.mApp.getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo().isAvailable();
    }

    public static String getPortraitUrl(String url) {
        //http://10.0.2.2:8080/oschina/images/uploads/user/472/945760_50.jpg?t=1378914342000
        return url.replace("2", "3");
    }

}


